const app = getApp()
// var utilMd5 = require('../utils/md5.js');
var md5 = require('../utils/newmd5.js')
// let token = null 
// wx.getStorage({
//   key: "token",
//   success: res => {
//     token = res.data || null
//   }
// })

const request = (url, options) => {
  // var timers =  setTimeout(()=>{
  //   wx.showLoading({
  //     title: '加载中...'
  //   })
  // },3000)

  // wx.showLoading({
  //   title:'正在努力加载...'
  // })
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token') || null;
    let config = {
      url: url,
      method: options.method,
      data: options.data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
      },
      success(request) {
        if (request.data.statusCode === 200) {
          resolve(request.data)
        } else if(request.data.statusCode === 401) {
          wx.navigateTo({
            url: '../login/login',
          })
          resolve(request.data)
        }else{
          wx.hideLoading()
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    }
    if(token){
      config.header.Authorization = `Bearer ${token}` // 看自己是否需要
    }
    wx.request(config)
  })
}

const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}

const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options
  })
}

module.exports = {
  get,
  post
}